/*
 * Package il.ac.biu.cs.grossmm.api.flow
 * File DataProcessorBase.java
 * 
 * This is a part of presence service framework API. 
 * See javadoc for more information.
 *  
 * Copyright (C) 2006 Grossmann Mark
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.

 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package il.ac.biu.cs.grossmm.api.flow;

import il.ac.biu.cs.grossmm.api.server.Component;
import il.ac.biu.cs.grossmm.api.server.ComponentManager;
import il.ac.biu.cs.grossmm.api.server.ServiceManager;
import il.ac.biu.cs.grossmm.api.server.Service;

/**
 * A base class to simplify implementation of a data processor.
 */
public abstract class DataProcessorBase implements Runnable, Component, Service {
	protected ActiveDataManager adm;

	protected Object admHint;

	protected String processorName;

	private boolean needThread;

	private Thread thread;

	private ProcessorState processorState;

	protected ComponentManager componentManager;

	protected ServiceManager serviceManager;

	private enum ProcessorState {
		STOPPED, STARTING, RUNNING, STOPPING
	}

	/**
	 * Creates a data processor which will automatically start a new thread when
	 * the associated service is started.
	 * 
	 * @param name
	 *            name of the data processor
	 */
	public DataProcessorBase(String name)
	{
		this(name, ActiveDataManager.class, true);
	}

	/**
	 * Creates a data processor which will or will not automatically start a new
	 * thread when the associated service is started depending on the parameter
	 * <tt>needThread</tt>.
	 * 
	 * @param name
	 *            name of the data processor
	 * @param needThread
	 *            if true, a new thread will be automatically startd when the
	 *            associated service is started
	 */
	public DataProcessorBase(String name, boolean needThread)
	{
		this(name, ActiveDataManager.class, needThread);
	}

	/**
	 * Creates a data processor which will use a custom hint to obtain active
	 * data manager and will or will not automatically start a new thread when
	 * the associated service is started depending on the parameter
	 * <tt>needThread</tt>.
	 * 
	 * @param name
	 *            name of the data processor
	 * @param admHint
	 *            a custom hint for active data manager
	 * @param needThread
	 *            if true, a new thread will be automatically startd when the
	 *            associated service is started
	 */
	public DataProcessorBase(String name, Object admHint, boolean needThread)
	{
		this.admHint = admHint;
		this.processorName = name;
		this.needThread = needThread;

		this.processorState = ProcessorState.STOPPED;
	}

	public void aborted(Object hint, Exception e) throws Exception
	{
		throw e;
	}

	public void terminated(Object serviceHint, Exception e) throws Exception
	{
		throw e;
	}

	public void setComponentManager(ComponentManager container)
		throws Exception
	{
		this.componentManager = container;
		adm = (ActiveDataManager) container.getComponent(admHint);
	}

	public synchronized void start(ServiceManager serviceManager)
		throws Exception
	{
		this.serviceManager = serviceManager;

		assert thread == null && processorState == ProcessorState.STOPPED;

		processorState = ProcessorState.STARTING;

		if (needThread) {

			System.out.println("Starting thread "+processorName+"...");
			thread = new Thread(this, processorName);
			thread.start();

			while (processorState == ProcessorState.STARTING) {
				wait();

				// for the case the thread crashed before
				// it called stopped()
				if (!thread.isAlive())
					break; // need to stop?
			}
			
			System.out.println("...Ok");

		} else {
			processorState = ProcessorState.RUNNING;
			System.out.println("---- STARTED W/O THREAD: "+processorName);
		}
	}

	public synchronized void stop(Exception exception)
	{
		if (thread == null || !thread.isAlive()) {
			processorState = ProcessorState.STOPPED;
			return;
		}

		if (processorState != ProcessorState.RUNNING)
			return;

		processorState = ProcessorState.STOPPING;
		notify();

		while (processorState != ProcessorState.STOPPED)
			try {
				wait();

				// for the case the thread crashed before
				// it called stopped()
				if (!thread.isAlive())
					break;
			} catch (InterruptedException e) {
				return;
			}

		assert !thread.isAlive();

		processorState = ProcessorState.STOPPED;
		thread = null;
	}

	/**
	 * Queries whether any associated threads should be terminated due to
	 * termination of the service
	 * 
	 * @return true iff the service is stopping
	 */
	protected boolean mustStop()
	{
		return processorState == ProcessorState.STOPPING;
	}

	protected synchronized void started()
	{
		System.out.println("---- STARTED: "+processorName);
		
		processorState = ProcessorState.RUNNING;
		
		notifyAll();
	}

	/**
	 * Should be called from the associated thread when startup process is
	 * finnished.
	 * 
	 */
	protected synchronized void stopped()
	{
		processorState = ProcessorState.STOPPED;
		notify();
	}
	
	/**
	 * When an exception situation occurs and service have to be terminated 
	 * because of it, normally this method is called and the service
	 * thread exits.
	 * 
	 */
	protected synchronized void stopped(Exception e)
	{
		serviceManager.terminated(e);
		processorState = ProcessorState.STOPPED;
		notify();
	}

	/**
	 * Should be called from the associated thread when termination process is
	 * finnished.
	 * 
	 */
	protected synchronized void waitForStop()
	{
		while (!mustStop())
			try {
				wait();
			} catch (InterruptedException e) {
			}
	}

	/**
	 * Implementation of this method must:
	 * <ul>
	 * <li>Call <tt>started</tt> when completely started (ready to provide a
	 * service).
	 * 
	 * <li>Terminate when <tt>mustStop</tt> returns true. Can use
	 * <tt>wait</tt> on this object to wait for this condition.
	 * 
	 * <li>Call <tt>stopped</tt> when completely stopped (before return),
	 * even when stopping abnormally.
	 * </ul>
	 */
	public void run()
	{
	}

	@Override
	public String toString()
	{
		return processorName;
	}
}
